import axios from 'axios'
import {
  Loading,
  Message
} from 'element-ui'

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 100000,
  publicEncrypt: false
})

// element加载页
let loadingInstance = null;
let requestNum = 0;
const addLoading = () => {
  requestNum++;
  if (requestNum == 1) {
    loadingInstance = Loading.service({
      lock: true,
      text: "请求加载中,请稍等...",
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.6)"
    });
  }
};
const cancelLoading = () => {
  // 取消loading 如果pending请求数量等于0，关闭loading
  requestNum--;
  if (requestNum === 0) loadingInstance.close();
};


// request拦截器
service.interceptors.request.use(config => {
  // 统一设置用户身份 token
  // 是否需要设置 token
  let token = process.env.VUE_APP_TOKEN;
  if (process.env.VUE_APP_ENV == "development") {
    config.headers["X-Oars-Token"] = `${token}`;
    config.headers.Authorization = `Bearer ${token}`;
  }
  // filebase接口认证
  // console.log('config', config)
  if (
    process.env.VUE_APP_ENV == "development" &&
    config.baseURL == "/filebase"
  ) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  // element加载动画
  if (config.loading) {
    addLoading()
  }

  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    const {
      loading = true
    } = res.config;
    if (loading) cancelLoading();
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    let errorCode = {
      '401': '认证失败，无法访问系统资源',
      '403': '当前操作没有权限',
      '404': '访问资源不存在',
      'default': '系统未知错误，请反馈给管理员'
    }

    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code === 500) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200 && code != 10000) {
      Message({
        message: msg,
        type: 'error',
        // duration:0,
      })
      return Promise.reject('error')
    } else {
      if (res.data.state) {
        Message({
          message: msg,
          type: res.data.state
        })
      }
      return res.data
    }
  },
  error => {
    const {
      loading = true
    } = error.config;
    if (loading) cancelLoading();
    console.log('err' + error)
    let {
      message
    } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
